package com.vincent.template.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

/**
 * @Author Vincent Wang
 * @Date 2020/11/2 15:04
 */
public class FieldUtil {

    private FieldUtil() {
    }

    /**
     * 获取字段的get方法名
     * @param field
     * @return
     */
    public static String getMethodName(String field) {
        return "get" + upperCaseFirst(field);
    }

    /**
     * 根据get/is方法名获取对应的字段名
     * @param method
     * @return
     */
    public static String getFieldName(String method) {
        if (StringUtils.isBlank(method) && !method.startsWith("get") && !method.startsWith("is")) {
            return null;
        }
        if (method.startsWith("get")) {
            return lowerCaseFirst(method.substring(3));
        }
        return lowerCaseFirst(method.substring(2));
    }

    /**
     * 判断obj是否有值
     * @param obj
     * @return
     */
    public static boolean hasValue(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof String) {
            return StringUtils.isNotBlank((String) obj);
        }
        if (obj instanceof Collection<?>) {
            return CollectionUtils.isNotEmpty((Collection<?>) obj);
        }
        return true;
    }

    /**
     * 字符串首字母大写
     * @param str
     * @return
     */
    public static String upperCaseFirst(String str) {
        char[] charArr = str.toCharArray();
        char firstChar = charArr[0];
        if (firstChar >= 'a' && firstChar <= 'z') {
            charArr[0] = (char) (firstChar - 32);
        }
        return String.valueOf(charArr);
    }

    /**
     * 字符串首字母小写
     * @param str
     * @return
     */
    public static String lowerCaseFirst(String str) {
        char[] charArr = str.toCharArray();
        char firstChar = charArr[0];
        if (firstChar >= 'A' && firstChar <= 'Z') {
            charArr[0] = (char) (firstChar + 32);
        }
        return String.valueOf(charArr);
    }
}
